using System;
using Gtk;
using System.Threading;
using Mono.Unix;

namespace kedhlow
{
	class MainClass
	{
		public static void Main (string[] args)
		{
			KDB dbc; //Database connection object
			
			Application.Init();
			Catalog.Init("kedhlow","./locale"); //Init language catalogs
			
			SplashScreen splash = new SplashScreen(); //Create new splashscreen window
			
			GLib.Timeout.Add(100,new GLib.TimeoutHandler( delegate() { splash.PulseSplashProgress(); return true; } ));
			Thread thd = new Thread(delegate()
			{
				try
				{
					//Get user directory paths
					string UserDataDirectory = System.IO.Path.Combine(Environment.GetFolderPath(System.Environment.SpecialFolder.Personal),".kedhlow");
					string DBPath = System.IO.Path.Combine(UserDataDirectory,"kedhlow.db3");
					
					bool dbExists = false;
					
					Console.WriteLine("Checking for user directory");
					if(!System.IO.Directory.Exists(UserDataDirectory))
					{
						System.IO.Directory.CreateDirectory(UserDataDirectory);
					}
					
					//Thread.Sleep(1000); //Pause to simulate loading TO BE REMOVED
	
					Console.WriteLine("Checking for user database");
					if(System.IO.File.Exists(DBPath))
					{
						dbExists = true;
					}
					
					Console.WriteLine("Connecting to database");
					
					dbc = new KDB(DBPath);
					if(!dbExists)
					{
						//Database didnt exist, so has been created on connect:
						if(dbc.CreateInitialDatabase())
						{
							Console.WriteLine("New database created");
						}
						else
						{
							splash.SetSplashLabelText(Catalog.GetString("Failed to create database"));
							System.IO.File.Delete(DBPath);
							Thread.Sleep(1000);
							throw new Exception("Failed to create database");
							
						}
					}
	
					//Now that loading is complete, launch the main application from the main application thread
					Application.Invoke(
						delegate
						{
							Console.WriteLine("Initialising main window");
							Thread.Sleep(1000);
							MainWindow win = new MainWindow(dbc);
							win.ShowAll();
							splash.Destroy();
					  	});
				}
				catch (Exception excp)
				{
					splash.SetSplashLabelText(Catalog.GetString("Fatal error loading application"));
					Console.WriteLine(Catalog.GetString("Fatal error loading application") + ":");
					Console.WriteLine(excp.Message);
					Console.WriteLine(excp.StackTrace);
					
					splash.SetSplashLabelText(Catalog.GetString(excp.Message));	
				
					Application.Quit();
				}
			});

			thd.Start(); //Start loader thread
			Application.Run(); //Launch application
			
		}
	}
}

